import './index.scss'
import { Card, Form, Input, Button, message } from 'antd'
import logo from '@/assets/logo.png'
import { useDispatch } from 'react-redux'
import { fetchLogin } from '../../store/modules/user'
import { useNavigate } from 'react-router-dom'
import { useEffect } from 'react'

import { getToken } from '@/utils'

const Login = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()

  const finish = async (value) => {
    await dispatch(fetchLogin(value))
    navigate('/')
    message.success('login success')
  }

  const finishFailed = (value) => {
    console.log('finishFail', value)
  }

  useEffect(() => {
    if (getToken()) {
      navigate('/')
    }
  }, [navigate])

  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/* 登录表单 */}
        <Form validateTrigger="onBlur" onFinish={finish} onFinishFailed={finishFailed}>
          <Form.Item
            name="mobile"
            rules={[
              {
                required: true,
                message: 'please input your mobile'
              },
              {
                pattern: /^(\+?\d{1,4})?\s*-?\s*(\(?\d{1,4}\)?)\s*-?\s*(\d{1,4})\s*-?\s*(\d{1,4})$/,
                message: 'please input correct mobile'
              }
            ]}
          >
            <Input size="large" placeholder="请输入手机号 13262865073" />
          </Form.Item>
          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: 'please input your code'
              }
            ]}
          >
            <Input size="large" placeholder="请输入验证码 246810" />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}

export default Login